package com.ruoyi.web.api;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.course.domain.SysCourse;
import com.ruoyi.course.domain.SysCourseStudent;
import com.ruoyi.course.service.ISysCourseService;
import com.ruoyi.course.service.ISysCourseStudentService;
import com.ruoyi.web.controller.course.SysCourseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * 课程
 */
@RestController
@RequestMapping("/api/course")
public class CourseApi extends BaseController {
    @Autowired
    private ISysCourseService sysCourseService;
    @Autowired
    private SysCourseController sysCourseController;
    @Autowired
    private ISysCourseStudentService sysCourseStudentService;

    /**
     * 课程列表
     * @return
     */
    @RequestMapping("/list")
    public AjaxResult list(SysCourse sysCourse)
    {
        sysCourse.setReleaseStatus(0);  //已发布
        sysCourse.setDelFlag("0"); //未删除
        List<SysCourse> list = sysCourseService.selectSysCourseList(sysCourse);
        return AjaxResult.success(list);
    }
    //播放视频
    @RequestMapping("/playVideo")
    public void playVideo(long courseNo , HttpServletRequest req , HttpServletResponse response) throws Exception{
        String path = sysCourseService.getVideoPath(courseNo);
        sysCourseController.readVideo(new File(path) ,req ,response);
    }

    /**
     * 获取学习进度
     * @return
     */
    @GetMapping("/process")
    public AjaxResult process(SysCourseStudent sysCourseStudent)
    {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        sysCourseStudent.setUserId(loginUser.getUserId());
        sysCourseStudent = sysCourseStudentService.getByUserIdAndCourseNo(sysCourseStudent.getUserId(),sysCourseStudent.getCourseNo());
        return AjaxResult.success(sysCourseStudent);
    }

    /**
     * 提交学习进度
     * @return
     */
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody SysCourseStudent sysCourseStudent)
    {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        sysCourseStudent.setUserId(loginUser.getUserId());
        sysCourseStudent.setNickName(loginUser.getUsername());
        SysCourseStudent dbSysCourseStudent = sysCourseStudentService.updateSysCourseStudentProcess(sysCourseStudent);
        sysCourseStudent = sysCourseStudentService.getByUserIdAndCourseNo(dbSysCourseStudent.getUserId(),dbSysCourseStudent.getCourseNo());
        return AjaxResult.success(sysCourseStudent);
    }
}
